package com.qffx.moviebase.view;


import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.qffx.moviebase.R;
import com.qffx.moviebase.adapter.find.FindNewestAdapter;
import com.qffx.moviebase.bean.find.FindNewestEntity;
import com.qffx.moviebase.broadcast.NetWorkReceiver;
import com.qffx.moviebase.presenter.FindNewestPresenter;
import com.qffx.moviebase.utils.NetWorkUtils;
import com.qffx.moviebase.utils.common.FindRecyclerView;
import com.qffx.moviebase.view.impl.FindNewestView;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class FindNeweatFragment extends Fragment implements View.OnClickListener,
        FindNewestView, PullToRefreshBase.OnRefreshListener2, NetWorkReceiver.ICallBack {
    private View view;
    private TextView tv;
    private ImageView loading;
    private AnimationDrawable mDrawable;
    private FindNewestPresenter presenter;
    //未联网时或者数据加载失败时布局
    private RelativeLayout newest_content;
    private List<FindNewestEntity.RecommendsListBean> listBeen;
    private FindNewestAdapter adapter;
    private FindRecyclerView myRecyclerView;
    private DbUtils dbUtils;
    private List<FindNewestEntity.RecommendsListBean> dbList;
    private NetWorkReceiver receiver;
    private static int index = 0;

    public FindNeweatFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_find_neweat, container, false);

        init();
        return view;
    }

    private void init() {
        receiver = new NetWorkReceiver(this);

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        getActivity().registerReceiver(receiver, filter);


        dbUtils = DbUtils.create(getActivity());
        tv = (TextView) view.findViewById(R.id.newest_tv);
        loading = (ImageView) view.findViewById(R.id.loading);
        newest_content = (RelativeLayout) view.findViewById(R.id.newest_content);
        myRecyclerView = (FindRecyclerView) view.findViewById(R.id.recycle);
        mDrawable = (AnimationDrawable) loading.getBackground();
        listBeen = new ArrayList<>();
        try {
            Selector s = Selector.from(FindNewestEntity.RecommendsListBean.class);
            dbList = dbUtils.findAll(s);

            if (dbList != null) {
                adapter = new FindNewestAdapter(listBeen, getActivity());
            } else
                adapter = new FindNewestAdapter(listBeen, getActivity());

        } catch (DbException e) {
            e.printStackTrace();
        }
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        myRecyclerView.setMode(PullToRefreshBase.Mode.BOTH);
        myRecyclerView.getRefreshableView().setLayoutManager(manager);
        myRecyclerView.getRefreshableView().setAdapter(adapter);
        myRecyclerView.setOnRefreshListener(this);

        newest_content.setOnClickListener(this);
        presenter = new FindNewestPresenter(this, getActivity());


        presenter.getData(0);
        index += index;
        //判断是否有网络
        if (NetWorkUtils.isNetWorkAvailable(getActivity())) {
            newest_content.setVisibility(View.GONE);
            loading.setVisibility(View.VISIBLE);
            myRecyclerView.setVisibility(View.VISIBLE);
            mDrawable.start();
        } else {
            myRecyclerView.setVisibility(View.GONE);
            loading.setVisibility(View.GONE);
            tv.setText("似乎已断开与互联网的连接：-5");
        }

    }

    //点击图片重新加载
    @Override
    public void onClick(View view) {
        newest_content.setVisibility(View.GONE);
       // Toast.makeText(getActivity(), "aaaa", Toast.LENGTH_SHORT).show();
        if (!NetWorkUtils.isNetWorkAvailable(getActivity())) {
            newest_content.setVisibility(View.VISIBLE);
            loading.setVisibility(View.GONE);
        } else {
            myRecyclerView.setVisibility(View.VISIBLE);
            loading.setVisibility(View.VISIBLE);
            mDrawable.start();
            presenter.getData(0);

        }
    }

    @Override
    public void setDate(FindNewestEntity bean) {
        List<FindNewestEntity.RecommendsListBean> list = bean.getRecommendsList();
        mDrawable.stop();
        loading.setVisibility(View.GONE);
        for (int i = 0; i < list.size(); i++) {
            try {
                list.get(i).setTag(false);
                dbUtils.save(list.get(i));
            } catch (DbException e) {
                e.printStackTrace();
            }
        }

        myRecyclerView.onRefreshComplete();

        listBeen.addAll(list);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        if (NetWorkUtils.isNetWorkAvailable(getActivity())) {
            presenter.getData(0);
        } else {
            Toast.makeText(getActivity(), "无网络", Toast.LENGTH_SHORT).show();
            myRecyclerView.onRefreshComplete();
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        if (NetWorkUtils.isNetWorkAvailable(getActivity())) {
            presenter.getData(index);
        } else {
            Toast.makeText(getActivity(), "无网络", Toast.LENGTH_SHORT).show();
            myRecyclerView.onRefreshComplete();
        }
    }

    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(receiver);
        super.onDestroy();
        try {
            dbUtils.deleteAll(FindNewestEntity.RecommendsListBean.class);
            dbList.clear();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void getState(Boolean b) {
        myRecyclerView.onRefreshComplete();
        Toast.makeText(getActivity(), "无网络", Toast.LENGTH_SHORT).show();
        if (loading.getVisibility() == View.VISIBLE) {
            loading.setVisibility(View.GONE);
            newest_content.setVisibility(View.VISIBLE);
            myRecyclerView.setVisibility(View.GONE);
            tv.setText("似乎已断开与互联网的连接：-5");
        }
    }
}
